//
//  Message.m
//  Test
//
//  Created by mac on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "Message.h"
#import <objc/runtime.h>

@implementation Message

//- (instancetype)initWithDict:(NSDictionary*)dict
//{
//
//    if (self = [super init]) {
//        [self setValuesForKeysWithDictionary:dict];
//    }
//    return self;
//}
//+ (instancetype)messageWithDict:(NSDictionary*)dict
//{
//    return [[self alloc] initWithDict:dict];
//}

+ (instancetype)messageWithDict:(NSDictionary*)dict
{
    Message* message = [[Message alloc] init];

    // 根据模型的属性,自动赋值!
    NSArray* properties = [message getProperties];

    // 遍历属性数组,进行 KVC 赋值
    [properties enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL* stop) {
        // obj :属性
        NSString* key = obj;
        if (dict[key]) {
            [message setValue:dict[key] forKey:key];
        }
    }];
    return message;
}

- (NSArray*)getProperties
{
    // 用来存储类的属性个数
    unsigned int count;

    objc_property_t* propesties = class_copyPropertyList(self.class, &count);

    NSMutableArray* array = [NSMutableArray array];

    for (int i = 0; i < count; i++) {

        // pro :就是类的属性
        objc_property_t pro = propesties[i];

        const char* name = property_getName(pro);

        // C 的名称转换成 OC 的名称
        NSString* property = [[NSString alloc] initWithUTF8String:name];

        [array addObject:property];
    }
    return array;
}

@end
